package com.cnware.capture.model;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

import com.cnware.common.util.FolderUtil;
import com.cnware.common.util.SqliteDBUtil;

public class Workspace {
	private String workForder = "workspace";
	
	private static final String SPACE_DB = ".workspace";
	
	private ArrayList<Project> projectList = new ArrayList<Project>();
	
	public Workspace() {
		init();
	}
	
	public void init(){
		FolderUtil.checkFolder(this.workForder, true);
		loadPrject();
	}
	
	private void loadPrject(){
		Connection conn = null;
		try {
			conn = SqliteDBUtil.getConnection(workForder + "\\" + SPACE_DB);
			Statement stmt = conn.createStatement();
			stmt.setQueryTimeout(30);
			
			stmt.executeUpdate("create table if not exists project (" +
					"id INTEGER PRIMARY KEY," +
					"project_name TEXT NOT NULL," +
					"project_index INTEGER NOT NULL," +
					"project_folder TEXT NOT NULL," +
					"project_memo TEXT NOT NULL)");
			
			ResultSet rs = stmt.executeQuery("select * from project order by project_index desc");
			
			while(rs.next()){
				Project project = new Project(this, rs);
				project.init();
				this.projectList.add(project);
			}
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				if (conn != null)
					conn.close();
			} catch (SQLException ex) {
				// connection close failed.
				System.err.println(ex);
			}
		}
	}
	
	
	public String getWorkForder() {
		return workForder;
	}

	public void setWorkForder(String workForder) {
		this.workForder = workForder;
	}
	
	public ArrayList<Project> getProjectList(){
		return this.projectList;
	}
	
}
